package top.yueyazhui.mysql_audit_log.job;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DBBackup {

    @Value("${spring.datasource.username}")
    private String DB_USERNAME;
    @Value("${spring.datasource.password}")
    private String DB_PASSWORD;
    @Value("${spring.datasource.url}")
    private String DB_URL;
    private String DB_NAME;

    @Value("${yueyazhui.server.host}")
    private String HOST;
    @Value("${yueyazhui.server.username}")
    private String USERNAME;
    @Value("${yueyazhui.server.password}")
    private String PASSWORD;
    @Value("${yueyazhui.server.db-backup-path}")
    private String DB_BACKUP_PATH;

    @Scheduled(cron = "* * 5 * * ?")
    public void cron() {
        Pattern pattern = Pattern.compile("/\\w+\\?");
        Matcher matcher = pattern.matcher(DB_URL);
        while(matcher.find()){
            DB_NAME = DB_URL.substring(matcher.start() + 1, matcher.end() - 1);
        }
        String cmd = "mysqldump -u'" + DB_USERNAME + "' -p'" + DB_PASSWORD + "' " + DB_NAME + " > " + DB_BACKUP_PATH + DB_NAME + "_$(date +%Y%m%d%H%M%S).sql";
        System.out.println("cmd = " + cmd);
        try {
            Connection connection = new Connection(HOST);
            connection.connect();
            boolean authenticate = connection.authenticateWithPassword(USERNAME, PASSWORD);
            if (!authenticate) {
                throw new RuntimeException("服务器认证失败");
            }
            Session session = connection.openSession();
            session.execCommand(cmd);
            session.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
